package fuck.handler;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteOrder;
import java.util.Iterator;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.QualifiedName;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.StringLiteral;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.PlatformUI;

import ast.JdtAstUtil;
import ast.TypeDeclaratinVisitor;

import fuck.ActionContext;

public class AddJavaCodeHandler implements Handler {

	private ActionContext context;

	public AddJavaCodeHandler(ActionContext context) {
		this.context = context;
	}

	@Override
	public void action(Object[] paramArrayOfObject) {
		if ((this.context.getSelection() != null) && ((this.context.getSelection() instanceof StructuredSelection)) && (!this.context.getSelection().isEmpty())) {

			// 选择的文件,可能是多选
			Iterator it = ((StructuredSelection) this.context.getSelection()).iterator();
			while (it.hasNext()) {
				Object obj = it.next();
				if ((obj instanceof org.eclipse.jdt.core.ICompilationUnit)) {
					org.eclipse.jdt.core.ICompilationUnit cu = (org.eclipse.jdt.core.ICompilationUnit) obj;
					
//					IProject project = cu.getJavaProject().getProject();
					//IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("VV");

					//IJavaProject javaProject = JavaCore.create(project);

					IJavaProject javaProject = cu.getJavaProject();
					try {
						// TODO maven这里需要修改
						IFolder srcFolder = javaProject.getProject().getFolder("src");
						
						if (!srcFolder.exists()) {
							srcFolder.create(true, true, null);
						}

						// 取某个java源代码,加入内容
						// eclipse创建代码
						IPackageFragmentRoot packageFragmentRoot = javaProject.findPackageFragmentRoot(srcFolder.getFullPath());

//						IPackageFragment packageFragment = packageFragmentRoot.getPackageFragment("ast");

						
//						IFile codefile = srcFolder.getFile("/ast/PluginAddCodeTest.java");
//						IFile codefile = srcFolder.getFile(cu.getPath());
						IFile codefile = ResourcesPlugin.getWorkspace().getRoot().getFile(cu.getPath());
						// 取得代码

						// CompilationUnit comp =
						// JdtAstUtil.getCompilationUnit(codefile.getFullPath().toString());

						InputStream codeins = codefile.getContents();
						ASTParser parser = ASTParser.newParser(AST.JLS4);
						
						StringBuilder sb = new StringBuilder();
						BufferedReader br = new BufferedReader(new InputStreamReader(codeins));
						String readLine = br.readLine();
						while (null != readLine) {
							sb.append(readLine).append("\n");
							readLine = br.readLine();
						}

						String oldcode = sb.toString();
						codeins.close();
						
						//使用AST分析代码,取得字段信息
						parser.setSource(oldcode.toCharArray());
						parser.setKind(ASTParser.K_COMPILATION_UNIT);
						CompilationUnit comp = (CompilationUnit) parser.createAST(null);

						TypeDeclaratinVisitor typeDeclaratinVisitor = new TypeDeclaratinVisitor();
						comp.accept(typeDeclaratinVisitor);
						TypeDeclaration classDec = typeDeclaratinVisitor.getTc();
						
						if(null == classDec){
							context.getMcs().println("类文件格式有问题, 找不到 TypeDeclaration");
						}
						int endIndex = sb.lastIndexOf("}");//结束符,从结束符开始添加新代码
						
						sb.delete(endIndex, sb.length());
						
						
						//MessageDialog.openError(context.getShell(), "错误", "该方法已经存在!");
						
						//新加的方法
						sb.append("\t/**插件自动生成的方法*/\n");
						sb.append("\tpublic void newaddMethod(){\n\n\t}");
						
						sb.append("\n}");
						//这里修改了代码会自动保存
						codefile.setContents(new ByteArrayInputStream(sb.toString().getBytes()), true, false, null);
						
//						codefile.appendContents(new ByteArrayInputStream(comp.toString().getBytes()), false, false, null);
						
						//读取源码,修改后再添加进来,格式会乱,还是用FreeMark,先解析类字段,然后生成代码
//						packageFragment.createCompilationUnit("PluginAddCodeTest.java", comp.toString(), false, new NullProgressMonitor());
						
						System.out.println(comp.toString());
						
						
						//不使用ast创建代码了
//						AST ast = comp.getAST();
//
//						MethodDeclaration methodDec = ast.newMethodDeclaration();
//
//						SimpleName methodName = ast.newSimpleName("helloWorld");
//						Modifier methodModifier = ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
//						Block methodBody = ast.newBlock();
//
//						// 设置方法节点
//						methodDec.setName(methodName);// 方法名
//						methodDec.modifiers().add(methodModifier);// 方法可见性
//						methodDec.setBody(methodBody); // 方法体
//
//						// 将方法节点连接为类节点的子节点
//						classDec.bodyDeclarations().add(methodDec);
//						
//						/*
//						 * public class HelloWorld { public HelloWorld(){
//						 * System.out.println("Hello World!"); }}
//						 */
//						MethodInvocation methodInv = ast.newMethodInvocation();
//
//						SimpleName nameSystem = ast.newSimpleName("System");
//						SimpleName nameOut = ast.newSimpleName("out");
//						SimpleName namePrintln = ast.newSimpleName("println");
//
//						// 连接‘System’和‘out’
//						// System.out
//						QualifiedName nameSystemOut = ast.newQualifiedName(nameSystem, nameOut);
//
//						// 连接‘System.out’和‘println’到MethodInvocation节点
//						// System.out.println()
//						methodInv.setExpression(nameSystemOut);
//						methodInv.setName(namePrintln);
//
//						// ”Hello World!”
//						StringLiteral sHelloworld = ast.newStringLiteral();
//						sHelloworld.setEscapedValue("\"Hello World!\"");
//
//						// System.out.println(“Hello World!”)
//						methodInv.arguments().add(sHelloworld);
//
//						// 将方法调用节点MethodInvocation连接为表达式语句ExpressionStatement的子节点
//						// System.out.println(“Hello World!”);
//						ExpressionStatement es = ast.newExpressionStatement(methodInv);
//
//						// 将表达式语句ExpressionStatement连接为方法节点的点
//						methodBody.statements().add(es);
						
//						codefile.delete(false, new NullProgressMonitor());
						
						
				
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}

		}
	}

}
